package com.leonzx.base.controller.email;

import com.leonzx.base.config.pager.Page;
import com.leonzx.base.config.pager.PageInfo;
import com.leonzx.base.controller.base.BaseController;
import com.leonzx.base.entity.email.MailHistory;
import com.leonzx.base.entity.email.UserMail;
import com.leonzx.base.entity.system.BaseFile;
import com.leonzx.base.service.file.FileUploadService;
import com.leonzx.base.service.mail.MailHistoryService;
import com.leonzx.base.service.mail.UserMailService;
import com.leonzx.base.service.system.BaseFileService;
import com.leonzx.base.utils.Constants;
import com.leonzx.base.utils.FileUtils;
import com.leonzx.base.utils.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:chen
 * @Description:
 * @Date: 2018-07-09 11:09
 */
@RestController
@RequestMapping("/ajax/email/")
public class AjaxEmailController extends BaseController {


    @Autowired
    private UserMailService userMailService;
    @Autowired
    private BaseFileService baseFileService;
    @Autowired
    private FileUploadService fileUploadService;
    @Autowired
    private MailHistoryService mailHistoryService;

    /**
     * ajax获取人员信息
     *
     * @param page
     * @param p
     * @param q
     * @param id
     * @return
     */
    @RequestMapping("/userMail/select2")
    public Map<String, Object> selectEmail(@PageInfo(pageSize = Page.PAGE_SIZE, orderBy = "bu.username", orderDiv = Page.Sort.DESC) Page<UserMail> page, Long p, String q, String id) {
        Map<String, Object> data = new HashMap<>();
        if (StringUtils.isNotBlank(q)) {
            q = q.trim();
        }
        List<UserMail> userMails = userMailService.findUserMailByMailIsNotNull(id, q, currentUser().getId());
        page.setResult(userMails);
        long totalCount = page.getTotalCount();
        data.put("items", userMails);
        data.put("totalCount", totalCount);
        return data;
    }

    /**
     * 保存附件
     *
     * @Author chen
     * @Date 2018/7/10 13:46
     */
    @RequestMapping("/userMail/fileUpload")
    public Map<String, Object> ajaxUploadFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> data = new HashMap<>();
        String newFileName = UUIDUtils.getUUID();
        String oldName = file.getOriginalFilename();
        int index = oldName.lastIndexOf(".");
        //判断是否已经生成过
        String newName = newFileName + oldName.substring(index); //新文件名
        String path = Constants.FILE_QZ + File.separator + Constants.FILE_TYPE_EMAIL_FILE+ File.separator + newFileName + File.separator + newName;
        fileUploadService.upload(file, path);
        String serviceFilePath = FileUtils.uploadServiceFile(file, newFileName, Constants.FILE_QZ, Constants.FILE_TYPE_EMAIL_FILE, request, response);
        BaseFile baseFile = baseFileService.saveBaseFile(newName, file.getOriginalFilename(), serviceFilePath, currentUser().getId(),
                Constants.FILE_QZ, Constants.FILE_TYPE_EMAIL_FILE, Constants.BASE_FILE_N);
        data.put("baseFile", baseFile);
        return data;
    }

    /**
     * 删除oss上的附件及服务器上的附件
     *
     * @Author chen
     * @Date 2018/7/12 10:21
     */
    @RequestMapping("/baseFile/del")
    public Map<String, Object> delFile(String id, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> data = new HashMap<>();
        try {
            baseFileService.delBaseFile(id, request, response);
            addSuccessMessage(data, "删除成功");
        } catch (Exception e) {
            logger.error("删除失败", e);
            addFailMessage(data, "删除失败");
        }
        return data;
    }

    /**
     * 收件箱列表
    *@Author chen
    *@Date 2018/7/13 15:45
    */
    @RequestMapping("/mailHistory/list")
    public Map<String, Object> list(MailHistory mailHistory, @PageInfo(pageSize = Page.PAGE_SIZE, orderBy = "bmh.create_time") Page<MailHistory> page) {
        Map<String, Object> result = getMap();
        try {
            mailHistory.setUserId(currentUser().getId());
            List<MailHistory> mailHistories = mailHistoryService.findAllMailHistory(mailHistory);
            page.setResult(mailHistories);
            result.put("count", page.getTotalCount());
            result.put("data", mailHistories);
            result.put("code", "0");
            result.put("msg", "加载完成");
        } catch (Exception e) {
            logger.error("获取邮件数据失败", e);
            addFailMessage(result, "获取邮件数据失败");
        }
        return result;
    }
}
